home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C12 / Smartp.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.5 KB  |  76 lines

  1. //: C12:Smartp.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Smart pointer example
  7. #include <iostream>
  8. #include <cstring>
  9. using namespace std;
  10.  
  11. class Obj {
  12.   static int i, j;
  13. public:
  14.   void f() { cout << i++ << endl; }
  15.   void g() { cout << j++ << endl; }
  16. };
  17.  
  18. // Static member definitions:
  19. int Obj::i = 47;
  20. int Obj::j = 11;
  21.  
  22. // Container:
  23. class ObjContainer {
  24.   static const int sz = 100;
  25.   Obj* a[sz];
  26.   int index;
  27. public:
  28.   ObjContainer() {
  29.     index = 0;
  30.     memset(a, 0, sz * sizeof(Obj*));
  31.   }
  32.   void add(Obj* obj) {
  33.     if(index >= sz) return;
  34.     a[index++] = obj;
  35.   }
  36.   friend class Sp;
  37. };
  38.  
  39. // Iterator:
  40. class Sp {
  41.   ObjContainer* oc;
  42.   int index;
  43. public:
  44.   Sp(ObjContainer* objc) {
  45.     index = 0;
  46.     oc = objc;
  47.   }
  48.   // Return value indicates end of list:
  49.   int operator++() { // Prefix
  50.     if(index >= oc->sz) return 0;
  51.     if(oc->a[++index] == 0) return 0;
  52.     return 1;
  53.   }
  54.   int operator++(int) { // Postfix
  55.     return operator++(); // Use prefix version
  56.   }
  57.   Obj* operator->() const {
  58.     if(oc->a[index]) return oc->a[index];
  59.     static Obj dummy;
  60.     return &dummy;
  61.   }
  62. };
  63.  
  64. int main() {
  65.   const int sz = 10;
  66.   Obj o[sz];
  67.   ObjContainer oc;
  68.   for(int i = 0; i < sz; i++)
  69.     oc.add(&o[i]); // Fill it up
  70.   Sp sp(&oc); // Create an iterator
  71.   do {
  72.     sp->f(); // Smart pointer calls
  73.     sp->g();
  74.   } while(sp++);
  75. } ///:~
  76.